<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <el-tabs v-model="activeName">
          <el-tab-pane label="用户管理" name="first">
            <!-- 按钮 -->
            <el-button v-if="checkPemission('settings_add')" size="small" type="primary" @click="clickShowAdd">新增角色</el-button>
            <!-- 表格 -->
            <el-table
              v-loading="isLoading"
              element-loading-background="rgba(255, 255, 255, 0.9)"
              :data="list"
            >
              <el-table-column label="序号" width="100" type="index" :index="indexMethod" />
              <el-table-column label="角色" width="240" prop="name" />
              <el-table-column label="描述" prop="description" />
              <el-table-column label="操作" width="300">
                <template #default="{ row }">
                  <el-button size="small" type="success" @click="handleAssign(row.id)">分配权限</el-button>
                  <el-button :disabled="!checkPemission('settings_edit')" size="small" type="primary" @click="handleEdit(row.id)">编辑</el-button>
                  <el-button size="small" type="danger" @click="handleDel(row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <!--
              current-page 当前页
              page-sizes 可供选择的，每页条数列表
              page-size  当前生效的，每页条数
              total 总条数

              @size-change    每页条数    每页2条 => 每页4条
              @current-change 当前页变化  当前页1 => 当前页2
             -->
            <el-pagination
              :current-page="page"
              :page-sizes="[1, 2, 3, 4, 5]"
              :page-size="pagesize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </el-tab-pane>

          <el-tab-pane label="公司信息">
            <!-- 警告信息 -->
            <el-alert
              title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改"
              type="info"
              show-icon
              :closable="false"
            />
            <!-- 表单 -->
            <el-form label-width="120px" style="margin-top:50px">
              <el-form-item label="公司名称">
                <el-input v-model="companyForm.name" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input v-model="companyForm.companyAddress" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input v-model="companyForm.mailbox" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="备注">
                <el-input v-model="companyForm.remarks" type="textarea" :rows="3" disabled style="width:400px" />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>

    <!-- 添加的对话框 -->
    <el-dialog :title="showTitle" :visible="showDialog" @close="closeDialog">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="form.name" type="text" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="form.description" type="text" placeholder="请输入角色描述" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button size="small" @click="closeDialog">取消</el-button>
        <el-button size="small" type="primary" @click="submit">确认</el-button>
      </template>
    </el-dialog>

    <!-- 分配权限的弹层 -->
    <el-dialog
      title="分配权限"
      :visible="showAssignDialog"
      @close="closeAssignDialog"
      @open="openDialog"
    >

      <!--
        show-checkbox 是否显示复选框
        default-expand-all 是否默认展开
        check-strictly 父子是否不需要关联
        data 树形数据
        props 配置树形配置项 label children
       -->
      <el-tree
        ref="tree"
        v-loading="loadingTree"
        show-checkbox
        default-expand-all
        node-key="id"
        :check-strictly="true"
        :data="permissionData"
        :props="{ label: 'name' }"
      />

      <template #footer>
        <div style="text-align: right;">
          <el-button @click="closeAssignDialog">取消</el-button>
          <el-button type="primary" @click="clickSubmit">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { reqAddRole, reqAssignPerm, reqDeleteRole, reqGetRoleDetail, reqGetRoleList, reqUpdateRole } from '@/api/setting'
import { reqGetCompanyById } from '@/api/company'
import { mapState } from 'vuex'
import { reqGetPermissionList } from '@/api/permission'
import { tranListToTreeData } from '@/utils'
import hello from '@/mixins/hello'
import permission from '@/mixins/permission'
export default {
  name: 'Setting',
  mixins: [hello, permission],
  data() {
    return {
      title: '角色设置模块',
      activeName: 'first',
      list: [],
      page: 1,
      pagesize: 5,
      total: 0,
      isLoading: false,
      showDialog: false,
      form: {
        name: '',
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: ['blur', 'change'] }
        ],
        description: [
          { required: true, message: '请输入角色名称', trigger: ['blur', 'change'] }
        ]
      },
      companyForm: {
        name: '',
        companyAddress: '',
        mailbox: '',
        remarks: ''
      },
      showAssignDialog: false,
      roleId: '',
      permissionData: [], // 存储权限数据
      loadingTree: false
    }
  },
  computed: {
    ...mapState('user', ['userInfo']),
    showTitle() {
      return this.form.id ? '编辑角色' : '添加角色'
    }
  },
  created() {
    this.getRoleList()
    this.getCompanyInfo() // 获取公司信息
  },
  methods: {
    // 给角色分配权限
    async openDialog() {
      this.loadingTree = true

      // 请求数据，渲染树形列表
      const { data } = await reqGetPermissionList()
      const treeData = tranListToTreeData(data, '0')
      this.permissionData = treeData

      // 根据角色id，获取原本的角色权限数据
      const { data: { permIds }} = await reqGetRoleDetail(this.roleId)

      // 设置tree，进行回显
      // 员工id：604f7df5f900be1850edb152
      // 社保id：604f7e50f900be1850edb155
      this.$refs.tree.setCheckedKeys(permIds)

      setTimeout(() => (this.loadingTree = false), 300)
    },
    // 确认分配提交
    async  clickSubmit() {
      // 1. 获取用户选择的权限 ids
      const arr = this.$refs.tree.getCheckedKeys()

      // 2. 发送请求进行权限分配
      await reqAssignPerm({
        id: this.roleId,
        permIds: arr
      })

      // 3. 给个提示，重新渲染, 关闭弹框
      this.$message.success('分配成功')
      this.showAssignDialog = false
      this.getRoleList()
    },
    // -------------------------------------------------
    handleAssign(id) {
      this.roleId = id
      this.showAssignDialog = true
    },
    closeAssignDialog() {
      this.showAssignDialog = false
    },
    async getCompanyInfo() {
      const { data } = await reqGetCompanyById(this.userInfo.companyId)
      this.companyForm = data
    },
    async submit() {
      await this.$refs.form.validate()

      if (this.form.id) {
        await reqUpdateRole(this.form)
        this.$message.success('修改成功')
      } else {
        await reqAddRole(this.form)
        this.$message.success('添加成功') // 提示
      }

      this.closeDialog() // 关闭弹框
      this.getRoleList() // 重新渲染
    },
    closeDialog() {
      this.showDialog = false
      // 重置内容
      this.form = {
        name: '',
        description: ''
      }
      // 重置状态
      this.$refs.form.resetFields()
    },
    clickShowAdd() {
      this.showDialog = true
    },
    async getRoleList() {
      this.isLoading = true
      const res = await reqGetRoleList(this.page, this.pagesize)
      this.list = res.data.rows
      this.total = res.data.total

      setTimeout(() => {
        this.isLoading = false
      }, 300)
    },
    async handleDel(id) {
      await reqDeleteRole(id)
      this.$message.success('删除成功')
      // 注意：一旦当前页的最后一条数据，都被删除了，那么应该渲染上一页了，page--
      if (this.list.length === 1 && this.page > 1) {
        // 让当前页减一
        this.page = this.page - 1
      }
      this.getRoleList()
    },
    handleSizeChange(val) {
      // console.log(`每页条数变化 每页${val}条`)
      // 更新每页条数
      this.pagesize = val
      // 重置成第一页，因为原来能访问的页码数变化了，可能在访问一些不存在的页码（闭坑）
      this.page = 1
      // 重新渲染
      this.getRoleList()
    },
    handleCurrentChange(val) {
      // console.log(`当前页变化 当前页，第${val}页`)
      // 更新当前页
      this.page = val
      // 重新请求渲染
      this.getRoleList()
    },
    indexMethod(index) {
      // 当前页不变，算前面有多少个
      // index + 1 正常序号
      // (this.page-1) * this.pagesize 前面页数所有的数量
      return index + 1 + (this.page - 1) * this.pagesize
    },

    async handleEdit(id) {
      // 1. 发请求获取数据，回显
      const res = await reqGetRoleDetail(id)
      this.form = res.data
      // 2. 显示弹层
      this.showDialog = true
    }
  }
}
</script>

<style lang="scss" scoped>
.el-table {
  margin: 20px 0;
}
</style>
